package org.hd.taobao.config;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author: Ben
 * @Date: 2020/3/23 12:56
 */

public class DbPoolConnection {
    /*
    加载,链接druid,初始化数据库连接池
     */
    private static DbPoolConnection databasePool = null;
    private static DataSource dataSource = null;

    static {
        Properties properties = new Properties();
        try {
            InputStream inputStream=DbPoolConnection.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(inputStream);
//            new InputStreamReader(new FileInputStream("F:\\code\\IdeaProject\\travel\\src\\main\\resources\\druid.properties"))
        } catch (IOException e) {
            e.printStackTrace();
        }
//            loadPropertyFile("./druid.properties");
        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private DbPoolConnection() {
    }

    public static synchronized DbPoolConnection getInstance() {
        if (null == databasePool) {
            databasePool = new DbPoolConnection();
        }
        return databasePool;
    }

    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
}
//        public static Properties loadPropertyFile(String fullFile) {
//
//            if (null == fullFile || fullFile.equals(""))
//            {
//                throw new IllegalArgumentException("Properties file path can not be null : " + fullFile);
//            }
//            File webRootPath= new File(DbPoolConnection.class.getResource("").getPath());
//            InputStream inputStream = null;
//            Properties p = null;
//            try {
//                inputStream = new FileInputStream(new File(webRootPath
//                        + File.separator + fullFile));
//                p = new Properties();
//                p.load(inputStream);
//            } catch (FileNotFoundException e) {
//                throw new IllegalArgumentException("Properties file not found: " + fullFile);
//            } catch (IOException e) {
//                throw new IllegalArgumentException("Properties file can not be loading: " + fullFile);
//            } finally {
//                try {
//                    if (inputStream != null) {
//                        inputStream.close();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            return p;
//        }
//    }

